package com.gxar.quick.ar.server.base.controller;

import com.gxar.common.entity.PageResult;
import com.gxar.common.entity.Result;
import com.gxar.common.entity.login.LoginUserThread;
import com.gxar.common.entity.login.UserProfile;
import com.gxar.common.exception.APIRuntimeException;
import com.gxar.common.warning.ApiLog;
import com.gxar.quick.ar.server.base.common.properties.UserProperties;
import com.gxar.quick.ar.server.base.facade.UserFacade;
import com.gxar.quick.ar.server.base.model.ResultCodeEnum;
import com.gxar.quick.ar.server.base.model.user.vo.request.BatchDeleteUserRequest;
import com.gxar.quick.ar.server.base.model.user.vo.request.ChangeConfigRequest;
import com.gxar.quick.ar.server.base.model.user.vo.request.CreateUserRequest;
import com.gxar.quick.ar.server.base.model.user.vo.request.UpdateUserRequest;
import com.gxar.quick.ar.server.base.model.user.vo.response.*;
import com.gxar.quick.ar.server.db.service.ExchangeItemService;
import com.gxar.quick.ar.server.db.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * @author linsy
 * @version 1.0
 * @created 2024/1/26 14:02
 */
@Api(tags = "管理端用户接口")
@RestController
@RequestMapping("/admin/api/users")
@RequiredArgsConstructor
@Slf4j
public class AdminUserController {

    private final UserProperties userProperties;
    private final UserService userService;
    private final ExchangeItemService exchangeItemService;
    private final UserFacade userFacade;

    @ApiOperation("变更配置")
    @PostMapping("/change-config")
    public Result<UserConfigResponse> changeConfig(@RequestBody ChangeConfigRequest changeConfigRequest) {
        UserProfile userProfile = LoginUserThread.get();
        List<String> bPhonePrefix = userProperties.getBPhonePrefix();
        String phonePrefix = userProfile.getMobile().substring(0, 9);
        if (!bPhonePrefix.contains(phonePrefix)) {
            return Result.error(ResultCodeEnum.NO_PERMISSION_CHANGE_CONFIG);
        }
        UserConfigResponse response = userService.changeConfig(userProfile, changeConfigRequest);
        return Result.success(response);
    }

    @ApiOperation("意见反馈列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page_num", value = "页码", dataType = "number"),
            @ApiImplicitParam(name = "page_size", value = "页记录数", dataType = "number"),
            @ApiImplicitParam(name = "product_category", value = "产品类别，0-QuickAR,1-货+AR", dataType = "string"),
    })
    @GetMapping("/feedbacks")
    public Result<PageResult<FeedbackListResponse>> feedbackList(@RequestParam(name = "page_num", defaultValue = "1") int pageNum,
                                                                 @RequestParam(name = "page_size", defaultValue = "10") int pageSize,
                                                                 @RequestParam(name = "product_category", required = false) String productCategory) {
        return userService.feedbackList(pageNum, pageSize, productCategory);
    }

    @ApiOperation("用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page_num", value = "页码", dataType = "number"),
            @ApiImplicitParam(name = "page_size", value = "页记录数", dataType = "number"),
            @ApiImplicitParam(name = "user_id", value = "用户ID", dataType = "number"),
            @ApiImplicitParam(name = "phone", value = "手机号", dataType = "string"),
            @ApiImplicitParam(name = "template_number", value = "模板数量", dataType = "number"),
            @ApiImplicitParam(name = "created_at_start", value = "创建开始日期", dataType = "string"),
            @ApiImplicitParam(name = "created_at_end", value = "创建结束日期", dataType = "string"),
            @ApiImplicitParam(name = "updated_at_start", value = "更新开始日期", dataType = "string"),
            @ApiImplicitParam(name = "updated_at_end", value = "更新结束日期", dataType = "string"),
    })
    @GetMapping("")
    public Result<PageResult<AdminUserPageResponse>> pageList(@RequestParam(name = "page_num", defaultValue = "1") int pageNum,
                                                              @RequestParam(name = "page_size", defaultValue = "10") int pageSize,
                                                              @RequestParam(name = "user_id", required = false) Long userId,
                                                              @RequestParam(name = "phone", required = false) String phone,
                                                              @RequestParam(name = "template_number", required = false) Integer templateNumber,
                                                              @RequestParam(name = "created_at_start", required = false) String createdAtStart,
                                                              @RequestParam(name = "created_at_end", required = false) String createdAtEnd,
                                                              @RequestParam(name = "updated_at_start", required = false) String updatedAtStart,
                                                              @RequestParam(name = "updated_at_end", required = false) String updatedAtEnd) {
        UserProfile userProfile = LoginUserThread.get();
        if (Objects.isNull(userProfile)) {
            throw new APIRuntimeException(ResultCodeEnum.USER_NOT_EXIST);
        }

        return userService.pageList(userProfile, pageNum, pageSize, userId, phone, templateNumber, createdAtStart, createdAtEnd, updatedAtStart, updatedAtEnd);
    }

    @ApiOperation("用户兑换品列表（所有）")
    @GetMapping("/{phone}/exchange-item-page")
    public Result<PageResult<UserExchangeItemListResponse>> userExchangeItemPage(@RequestParam(name = "page_num", defaultValue = "1") int pageNum,
                                                                                 @RequestParam(name = "page_size", defaultValue = "10") int pageSize,
                                                                                 @PathVariable("phone") String phone) {
        return exchangeItemService.userExchangeItemPage(pageNum, pageSize, phone);
    }

    @ApiOperation("用户已经选择兑换品列表")
    @GetMapping("/{userId}/exchange_item")
    public Result<List<UserExchangeItemListResponse>> userExchangeItemList(@PathVariable("userId") Long userId) {
        return Result.success(exchangeItemService.userExchangeItemList(userId));
    }

    @ApiOperation("创建用户")
    @PostMapping("")
    @ApiLog
    public Result<CreateUserResponse> createUser(@RequestBody @Valid CreateUserRequest createUserRequest) {
        UserProfile userProfile = LoginUserThread.get();
        CreateUserResponse response = userFacade.createUser(userProfile, createUserRequest);
        return Result.success(response);
    }

    @ApiOperation("更新用户")
    @PutMapping("")
    @ApiLog
    public Result<UpdateUserResponse> updateUser(@RequestBody @Valid UpdateUserRequest updateUserRequest) {
        UserProfile userProfile = LoginUserThread.get();
        UpdateUserResponse response = userFacade.updateUser(userProfile, updateUserRequest);
        return Result.success(response);
    }

    @ApiOperation("用户授权")
    @PostMapping("/authorization")
    public Result<UserAuthorizationResponse> authorization() {
        UserProfile userProfile = LoginUserThread.get();
        Result<UserAuthorizationResponse> authorization = userService.authorization(userProfile);
        // 领取兑换品
        exchangeItemService.receiveExchangeItem(userProfile);
        return authorization;
    }

    @ApiOperation("删除用户")
    @DeleteMapping("/{user_id}")
    @ApiLog
    public Result<Boolean> deleteUser(@PathVariable("user_id") Long userId) {
        UserProfile userProfile = LoginUserThread.get();
        userService.deleteUser(userProfile, userId);
        return Result.success("删除成功", true);
    }

    @ApiOperation("删除用户")
    @DeleteMapping("/batch")
    @ApiLog
    public Result<Boolean> batchDeleteUser(@RequestBody @Valid BatchDeleteUserRequest request) {
        UserProfile userProfile = LoginUserThread.get();
        if (CollectionUtils.isEmpty(request.getUserIds())) {
            throw new APIRuntimeException(ResultCodeEnum.USER_IDS_NOT_EMPTY);
        }
        userService.batchDeleteUser(userProfile, request.getUserIds());
        return Result.success("删除成功", true);
    }

    @ApiOperation("导入用户")
    @PostMapping("/import")
    public Result<UserExchangeItemImportResponse> importUserExchangeItem(@RequestParam(name = "file", required = false) MultipartFile file) {
        UserExchangeItemImportResponse userExchangeItemImportResponse;
        try {
            UserProfile userProfile = LoginUserThread.get();
            userExchangeItemImportResponse = userFacade.importUserExchangeItem(userProfile, file);
        } catch (IOException e) {
            log.error("excel[{}]导入失败: {}", file.getName(), e.getMessage());
            throw new APIRuntimeException(ResultCodeEnum.EXCEL_ERROR);
        }
        return Result.success(userExchangeItemImportResponse);
    }

}
